import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class RegisterUser extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
    {
		doPost(request,response);
	}//doGet

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
    {
		RequestDispatcher dispatcher = null;
		try
		{
			String username = request.getParameter("username");
			String pwd = request.getParameter("password");
			String first = request.getParameter("first");
			String last = request.getParameter("last");
			String mobno = request.getParameter("mobno");
			int salary = Integer.parseInt(request.getParameter("salary"));
			int utype = Integer.parseInt(request.getParameter("utype"));
			int id=0;
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airtel","root","root");
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select userName from users where userName='"+username+"'");
			if(rs.next())
			{
				request.setAttribute("msg", new String("User already existed with username "+username));
				dispatcher = getServletContext().getRequestDispatcher("/jsp/Registration.jsp");
				dispatcher.forward(request,response);
			}
			else
			{
				rs = stmt.executeQuery("select max(id) from users");
				if(rs.next())
				{
					id = rs.getInt(1);
				}
				id++;
				int value = stmt.executeUpdate("insert into users values('"+id+"','"+username+"','"+pwd+"','"+first+"','"+last+"','"+mobno+"','"+salary+"','"+utype+"')");
				System.out.println("New User Created succesfully");
				request.setAttribute("msg", new String("New User Created succesfully with username "+username));
				dispatcher = getServletContext().getRequestDispatcher("/jsp/Registration.jsp");
				dispatcher.forward(request,response);
			}
        }//try
		catch(Exception e)
		{
            e.printStackTrace();
		}//catch
	}//doPost
}//class